<?php

declare(strict_types=1);

namespace App\Controller\Api;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Controller\AbstractController;
use App\Model\PssModel\Business;
use App\Model\PssModel\OrderPullLog;
use App\Service\Code\Normal;
use App\Model\PssModel\PddToken;
use App\Service\VendorClient\PddApi\ShopPddUserApiClient;
use App\Model\PssModel\PddRepushOrder;
use App\Service\AppService\SystemCacheConfigService;

/**
 * @Controller(prefix="/YunCangCustomOrderPullLog")
 * @author chenshubo
 */
class YunCangCustomOrderPullLogController extends AbstractController
{ 
    //需要处理隐藏显示铭感信息用户
    public $encrptUser = [
        'jd'    => '京东'
    ];
    
    /**
     * 获取对应sass化关务对应云仓订单捞单池里面的分页数据
     * @RequestMapping(path="SearchOrderList/{CustomOrderTag}", methods="post")
     * @return string[]
     */
    public function search(RequestInterface $request,$CustomOrderTag)
    {
        $params = $request->all();
        $page = 1;
        $limit = 10;
        $fields = ['id','bid','order_sn','status','contents','response_msg',"pdd_status",'cd',"md"];
        $bModel = Business::where('order_get_tag', $CustomOrderTag)->where('status',0)
                ->where('df',0)->where('verify_status',1)->where('user_source',2)
                ->where('user_type',2)->select('id', 'name');
        if($request->has('bid') && ctype_digit((string)$params['bid']) && $params['bid'] > 0){
            $bModel  = $bModel->where('id', $params['bid']);
        }
        $businessRes = $bModel->select(['name','id','user_tag'])->get()->toArray();
        if( empty($businessRes) ) {
            return Normal::returnCode(Normal::FAIL, "【{$CustomOrderTag}】对应的渠道商户不存在");
        }
        
        $businessArr = array_column($businessRes,null,'id');
        $bids = array_keys($businessArr);
        $model = OrderPullLog::whereIn('bid', $bids)->select($fields);
        if($request->has('page') && ctype_digit((string)$params['page']) && $params['page'] > 0){
            $page = $params['page'];
        }
        if($request->has('limit') && ctype_digit((string)$params['limit']) && $params['limit'] > 0){
            $limit = $params['limit'];
        }
        if($request->has('status') && in_array($params['status'], ['0','1','2','3','4','5','6','7'])){
            $model = $model->where('status', $params['status']);
        }

        if($request->has('order_sn') && !empty($params['order_sn'])){
            $model = $model->where('order_sn', $params['order_sn']);
        }
        if($request->has('order_start_time') && !empty($params['order_start_time'])){
            $orderStartTsp = strtotime($params['order_start_time']);
            if(!$orderStartTsp){
                return Normal::returnCode(Normal::FAIL, "【order_start_time】格式错误");
            }
            $model = $model->where('cd', '>=', $orderStartTsp);
        }
        if($request->has('order_end_time') && !empty($params['order_end_time'])){
            $orderEndTsp = strtotime($params['order_end_time']);
            if(!$orderEndTsp){
                return Normal::returnCode(Normal::FAIL, "【order_end_time】格式错误");
            }
            $model = $model->where('cd', '<=', $orderEndTsp);
        }
        if($request->has('push_start_time') && !empty($params['push_start_time'])){
            $pushStartTsp = strtotime($params['push_start_time']);
            if(!$pushStartTsp){
                return Normal::returnCode(Normal::FAIL, "【push_start_time】格式错误");
            }
            $model = $model->where('md', '>=', $pushStartTsp);
        }
        if($request->has('push_end_time') && !empty($params['push_end_time'])){
            $pushEndTsp = strtotime($params['push_end_time']);
            if(!$pushEndTsp){
                return Normal::returnCode(Normal::FAIL, "【push_end_time】格式错误");
            }
            $model = $model->where('md', '<=', $pushEndTsp);
        }
        $result = $model->orderBy('cd', 'desc')->paginate($limit);
        if($result->isEmpty()){
            return [
                'code'  => Normal::SUC,
                'msg'   => '获取成功',
                'count' => 0,
                'data'  => [],
            ];
        }
        
        $statusArr = array_column(OrderPullLog::$statusTextArr, 'statusName', 'status');
        $pushStatusArr = OrderPullLog::$pushStatusTextArr;
        $result->each(function ($item, $key) use($businessArr, $statusArr, $pushStatusArr) {
            $item->contents = $this->encrptData($item,$businessArr[$item['bid']]);
            $item->business_name = $businessArr[$item['bid']]['name']??'未定义';
            $item->status_name = $statusArr[$item['status']];
            $item->pdd_status_name = $pushStatusArr[$item['pdd_status']] ?? '未定义';
            $item->is_show_button = (in_array($item['status'],[3,4,7]) || ( in_array($item['pdd_status'],['2','3','6']) && $item['status'] == 0 ) ) ? 1: 0;
            $item->order_create_time = date('Y-m-d H:i:s', $item['cd']);
            $item->push_success_time = in_array($item['status'],['0','3','4']) ? '' : date('Y-m-d H:i:s',$item['md']);
            return $item;
        });
        return [
            'code'  => Normal::SUC,
            'msg'   => '获取成功',
            'count' => $result->total(),
            'data'  => $result->items(),
        ];
    }
    
    /**
     * 加密隐藏数据
     * @param array $orderItem
     * @param array $binfo
     */
    public function encrptData( $orderItem , array $binfo)
    {
        $orderItem = $orderItem->toArray();
        $contents = @json_decode($orderItem['contents'],true);
        if( isset($this->encrptUser[$binfo['user_tag']]) ) {
            if( !empty($contents) ) {
                
                $contents['waybillInfo']   = ArrayKeyStrToupper($contents['waybillInfo']);
                $contents['qingDanInfo']   = ArrayKeyStrToupper($contents['qingDanInfo']);
                $contents['listGoods']     = ArrayKeyStrToupper($contents['listGoods']);
                /* $contents['qingDanInfo']['PayTransactionId']            = str_pad("",mb_strlen($contents['qingDanInfo']['PayTransactionId']??'*********',"utf-8"),"*");
                $contents['qingDanInfo']['ReceiveNo']                   = str_pad("",mb_strlen($contents['qingDanInfo']['ReceiveNo'],"utf-8"),"*");
                $contents['waybillInfo']['BuyerIdNumber']               = str_pad("",mb_strlen($contents['waybillInfo']['BuyerIdNumber'],"utf-8"),"*");
                $contents['waybillInfo']['BuyerName']                   = str_pad("",mb_strlen($contents['waybillInfo']['BuyerName'],"utf-8"),"*");
                $contents['waybillInfo']['BuyerPhone']                  = str_pad("",mb_strlen($contents['waybillInfo']['BuyerPhone'],"utf-8"),"*");
                $contents['waybillInfo']['RecipientDetailedAddress']    = str_pad("",mb_strlen($contents['waybillInfo']['RecipientDetailedAddress'],"utf-8"),"*");
                $contents['waybillInfo']['RecipientName']               = str_pad("",mb_strlen($contents['waybillInfo']['RecipientName'],"utf-8"),"*");
                $contents['waybillInfo']['RecipientPhone']              = str_pad("",mb_strlen($contents['waybillInfo']['RecipientPhone'],"utf-8"),"*");
                $contents['waybillInfo']['RecipientProvincesName']      = str_pad("",mb_strlen($contents['waybillInfo']['RecipientProvincesName'],"utf-8"),"*");
                 */
                $contents['qingDanInfo']['PayTransactionId']            = '**********';
                $contents['qingDanInfo']['ReceiveNo']                   = '**********';
                $contents['waybillInfo']['BuyerIdNumber']               = '**********';
                $contents['waybillInfo']['BuyerName']                   = '**********';
                $contents['waybillInfo']['BuyerPhone']                  = '**********';
                $contents['waybillInfo']['RecipientDetailedAddress']    = '**********';
                $contents['waybillInfo']['RecipientName']               = '**********';
                $contents['waybillInfo']['RecipientPhone']              = '**********';
                $contents['waybillInfo']['RecipientProvincesName']      = '**********';
            }
        }
        return json_encode($contents,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * 获取对应sass化关务对应云仓订单捞单池里面的渠道商户数据菜单选择项列表
     * @RequestMapping(path="SearchChannelUserList/{CustomOrderTag}", methods="post")
     * @return string[]
     */
    public function searchChannelUserList(RequestInterface $request,$CustomOrderTag)
    {
        $result = Business::where('order_get_tag', $CustomOrderTag)->where('status',0)
                ->where('df',0)->where('verify_status',1)->where('user_source',2)
                ->where('user_type',2)->select('id as bid', 'name as userName')->get();
        if($result->isEmpty()){
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $result->toArray());
    }
    
    /**
     * 获取对应sass化关务对应云仓订单捞单池里面的状态枚举
     * @RequestMapping(path="SearchOrderStatusList/{CustomOrderTag}", methods="post")
     * @return string[]
     */
    public function SearchOrderStatusList(RequestInterface $request,$CustomOrderTag)
    {
         return Normal::returnCode(Normal::SUC, '获取成功', OrderPullLog::$statusTextArr);
    }
    
    /**
     * 获取对应sass化关务重新推送订单操作
     * @RequestMapping(path="RePushOrder/{CustomOrderTag}", methods="post")
     * @return string[]
     */
    public function rePushOrder(RequestInterface $request,$CustomOrderTag)
    {
        $order_id = $request->input('order_id');
        if( empty($order_id) ) {
            return Normal::returnCode(Normal::FAIL, "订单ID不能为空");
        }
        
        
        $orderRow = OrderPullLog::instance()->info(['id'=>$order_id]);
        if( empty($orderRow) ) {
            return Normal::returnCode(Normal::FAIL,"订单记录不存在");
        }
        
        //重新推送清单，仅多多可用
        $binfo = Business::instance()->getUserInfoByBid($orderRow['bid']);
        if( $binfo['user_tag']=='pdd' && in_array($orderRow['pdd_status'],['2','3','6']) && $orderRow['status'] == 0 )
        {
            //获取多多店铺信息
            $shop = PddToken::instance()->info(['auth_type' => 1,'bid' => $orderRow['bid']]);
            if( empty($shop) ) {
                return Normal::returnCode(Normal::FAIL,"当前渠道对应多多授权信息不存在");
            }
            
            //重新获取清关材料或者电子面单信息
            $result_query_pdd = (new ShopPddUserApiClient($shop))->reGetPddOrderClearanceAndPrintDataInfoByOrderLog($orderRow);
            if( !isset($result_query_pdd['pdd_status']) ) {
                return Normal::returnCode(Normal::FAIL,"当前数据业务状态不存在，请联系管理员核对");
            }
            
            OrderPullLog::instance()->where('id',$order_id)->update($result_query_pdd);
            return Normal::returnCode(Normal::SUC, "推送成功",$result_query_pdd);
        }
        
        if ($binfo['user_tag'] == 'pdd') {
            PddRepushOrder::instance()->insert([
                'order_sn' => $orderRow['order_sn'],
                'status'   => 1,
                'is_take'  => 0,
                'cd'       => time()
            ]);
        }
        
        try {
            OrderPullLog::where('id', $order_id)->update(['pull_times' => 4]);
        } catch (\Throwable $th) {
            return Normal::returnCode(Normal::FAIL, "重推失败【{$th->getMessage()}】");
        }
        return Normal::returnCode(Normal::SUC, "推送成功");
    }
    
    /**
     * 根据业务模型指定重新捞取订单
     * @RequestMapping(path="ReGetUserOrder", methods="post")
     * @return string[]
     */
    public function ReGetUserOrder(RequestInterface $request,$CustomOrderTag)
    {
        $order_id = $request->input('pull_order_id');
        if( empty($order_id) ) {
            return Normal::returnCode(Normal::FAIL, "捞单池pull_order_id不能为空");
        }
        
        $orderRow = OrderPullLog::instance()->info(['id'=>$order_id]);
        if( empty($orderRow) ) {
            return Normal::returnCode(Normal::FAIL,"订单记录不存在");
        }
        
        $binfo  = Business::instance()->getUserInfoByBid($orderRow['bid']);
        $config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('order_pull_log_config');
        try
        {
            $module = ucfirst($binfo['user_tag']);
            $class  = "App\\Service\\UserService\\SubUserRouterService\\{$module}";
            $method = "ReGetUserOrder";
            $result = $class::instance()->{$method}($config,$orderRow);
            return $result;
        }
        catch ( \Throwable $th) 
        {
            return Normal::returnCode(Normal::FAIL,"当前业务异常，原因：{$th->getMessage()}{$th->getLine()}{$th->getFile()}");
        }
    }
}